//
//  QiNiuUploadTask.m
//  AFNetworking
//
//  Created by jiaxuzhou on 2017/12/21.
//

#import "QiNiuUploadTask.h"
#import <QiniuSDK.h>
#import "YXUploadManager.h"
#import "MPTUploadRequest.h"
#import <MPTValidObject.h>
#import "MPTReachability.h"

@interface QiNiuUploadTask ()

@property (nonatomic,strong) QNUploadManager *upManager;

@end


@implementation QiNiuUploadTask

- (id)initWithVideo:(YXUploadVideo *)video {
    self = [super init];
    if (self) {
        self.video = video;
    }
    return self;
}

- (void)start {
    NSError *error;
    QNFileRecorder *file = [QNFileRecorder fileRecorderWithFolder:[NSHomeDirectory() stringByAppendingString:@"/Documents"] error:&error];
    if (!error) {
        
        /// 判断是不是免流量
        BOOL isMianLiuLiang = [[NSUserDefaults standardUserDefaults] boolForKey:@"isMianLiuLiang"];
        if (!isMianLiuLiang || [MPTReachability isViaWiFi])
        {
            QNConfiguration *config = [QNConfiguration build: ^(QNConfigurationBuilder *builder) {
                builder.recorder = file;
                builder.recorderKeyGen = ^NSString *(NSString *uploadKey, NSString *filePath) {
                    return uploadKey;
                };
            }];
            
            self.upManager = [QNUploadManager sharedInstanceWithConfiguration:config];
            
            if (![self.video.isThumbUploadComplate boolValue]) {
                [self uploadThumb];
            } else {
                [self uploadMedia];
            }
        }
        else
        {
            QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
                
                QNServiceAddress *up = [[QNServiceAddress alloc] init:@"http://up-miaopai-lt.qiniu.com" ips:@[@"124.160.148.39"]];
                QNServiceAddress *upBackup = [[QNServiceAddress alloc] init:@"http://up-miaopai-lt.qiniu.com" ips:@[@"101.71.22.70"]];
                builder.zone = [[QNFixedZone alloc] initWithUp:up upBackup:upBackup];
                builder.recorder = file;
                builder.recorderKeyGen = ^NSString *(NSString *uploadKey, NSString *filePath) {
                    return uploadKey;
                };
            }];
            
            self.upManager = [[QNUploadManager alloc] initWithConfiguration:config];
            if (![self.video.isThumbUploadComplate boolValue]) {
                [self uploadThumb];
            } else {
                [self uploadMedia];
            }
        }
        
    }
}

- (void)uploadThumb {
    NSDictionary *thumbParams = @{ @"x:token":self.video.token,
                                   @"x:scid":self.video.scid,
                                   @"x:file_md5":self.video.MD5?:@"",
                                   @"x:srwid":self.video.srwid,
                                   @"x:os":@"ios",
                                   @"x:version":[[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"],
                                   };
    
    YXRequestLogObject *object = [[YXRequestLogObject alloc] init];
    object.totalTime = [NSProcessInfo processInfo].systemUptime;
    object.sendByte  = 0;
    object.sendTime  = 0;
    object.receiveTime = 0.0f;
    
    QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        self.video.progress = [NSString stringWithFormat:@"%f",percent * 0.1];
        [self.uploadManager updateProgress:percent * 0.1 withVideo:self.video];
    } params:thumbParams checkCrc:YES cancellationSignal:^BOOL{
        return [self isCancelled];
    }];
    
    NSString *token = self.video.imageToken;
    if (!isValidNSString(token)) {
        NSDictionary *info = [MPTUploadRequest refreshQiniu:self.video type:@"image"];
        if ([info[@"status"] intValue] == 200) {
            self.video.imageToken = info[@"image_token"];
            [self uploadMedia];
        } else {
            self.video.uploadStatus = @"3";
            [self.uploadManager uploadFailedWithVideo:self.video];
            [self finish];
        }
    } else {
        [self.upManager putFile:self.video.thumb key:[NSString stringWithFormat:@"stream/%@_m.jpg",self.video.scid] token:token
                       complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                           
                           object.userInfo =  [NSString stringWithFormat:@"%@",info];
                           object.URL = [NSString stringWithFormat:@"%@",thumbParams];
                           object.IP  = @"";
                           object.totalTime    = ([NSProcessInfo processInfo].systemUptime - object.totalTime) * 1000;
                           object.httpStatusCode        = info.statusCode;
                           object.receiveByte           = 0;
                           object.sendByte              = 0;
                           object.httpResponseString    = [NSString stringWithFormat:@"%@",resp];
                           logger(@"UploadQiniu", extLog(object));
                           
                           
                           if ([resp[@"status"] intValue] == 200) {
                               [self resetCheckFailure];
                               self.video.progress = @"0.1";
                               self.video.isThumbUploadComplate = @"1";
                               [self uploadMedia];
                           } else if (info.statusCode == 401) {
                               [self checkFailure];
                               NSDictionary *info = [MPTUploadRequest refreshQiniu:self.video type:@"image"];
                               if ([info[@"status"] intValue] == 200) {
                                   self.video.imageToken = info[@"image_token"];
                                   [self uploadThumb];
                               }
                           } else  {
                               self.video.uploadStatus = @"3";
                               [self.uploadManager uploadFailedWithVideo:self.video];
                               [self finish];
                           }
                       } option:opt];
    }
}

- (void)uploadMedia {
    
    NSDictionary *videoParams = @{ @"x:token":self.video.token,
                                   @"x:scid":self.video.scid,
                                   @"x:os":@"ios",
                                   @"x:file_md5":self.video.MD5?:@"",
                                   @"x:srwid":self.video.srwid,
                                   @"x:version":[[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"],
                                   };
    
    YXRequestLogObject *object = [[YXRequestLogObject alloc] init];
    object.totalTime = [NSProcessInfo processInfo].systemUptime;
    object.sendByte  = 0;
    object.sendTime  = 0;
    object.receiveTime = 0.0f;
    
    QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        self.video.progress = [NSString stringWithFormat:@"%f",percent * 0.9 + 0.1];
        [self.uploadManager updateProgress:percent * 0.9 + 0.1 withVideo:self.video];
    } params:videoParams checkCrc:YES cancellationSignal:^BOOL{
        return [self isCancelled];
    }];
    
    NSString *token = self.video.mediaToken;
    
    if (!isValidNSString(token)) {
        NSDictionary *info = [MPTUploadRequest refreshQiniu:self.video type:@"video"];
        if ([info[@"status"] intValue] == 200) {
            self.video.mediaToken = info[@"media_token"];
            [self uploadMedia];
        } else {
            self.video.uploadStatus = @"3";
            [self.uploadManager uploadFailedWithVideo:self.video];
            [self finish];
        }
    } else {
        [self.upManager putFile:self.video.filePath key:[NSString stringWithFormat:@"stream/%@.mp4",self.video.scid] token:token
                       complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                           
                           object.userInfo =  [NSString stringWithFormat:@"%@",info];
                           object.URL = [NSString stringWithFormat:@"%@",videoParams];
                           object.IP  = @"";
                           object.totalTime    = ([NSProcessInfo processInfo].systemUptime - object.totalTime) * 1000;
                           object.httpStatusCode        = info.statusCode;
                           object.receiveByte           = 0;
                           object.sendByte              = 0;
                           object.httpResponseString    = [NSString stringWithFormat:@"%@",resp];
                           logger(@"UploadQiniu", extLog(object));
                           
                           
                           if ([resp[@"status"] intValue] == 200) {
                               [self resetCheckFailure];
                               self.video.progress = @"1";
                               self.video.isFinish = @"1";
                               self.video.isVideoUploadComplate = @"1";
                               [self.uploadManager uploadComplateWithVideo:self.video];
                               [self finish];
                           }else if (info.statusCode == 401) {
                               [self checkFailure];
                               NSDictionary *info = [MPTUploadRequest refreshQiniu:self.video type:@"video"];
                               if ([info[@"status"] intValue] == 200) {
                                   self.video.mediaToken = info[@"media_token"];
                                   [self uploadMedia];
                               }
                           }else if (info.statusCode == 579) {
                               [self checkFailure];
                               NSDictionary *info = [MPTUploadRequest finishQiniu:self.video];
                               if ( [info[@"status"] intValue]!= 200 ) {
                                   self.video.uploadStatus = @"3";
                                   [self.uploadManager uploadFailedWithVideo:self.video];
                                   [self finish];
                               }
                           } else {
                               self.video.uploadStatus = @"3";
                               [self.uploadManager uploadFailedWithVideo:self.video];
                               [self finish];
                           }
                       } option:opt];
    }
}

@end
